<script setup>
import { ref } from 'vue'
import { userEditPasswordService } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
// 表单提交数据
const formModel = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
// 表单对象
const formRef = ref()
// 表单校验规则
const rules = {
  old_pwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      pattern: /^\S{5,15}$/,
      message: '密码必须是5-15位非空字符',
      trigger: 'blur'
    }
  ],
  new_pwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === formModel.value.old_pwd) {
          return callback(new Error('新密码不能和原密码一致'))
        } else {
          return callback()
        }
      },
      trigger: 'blur'
    }
  ],
  re_pwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位非空字符',
      trigger: 'blur'
    },
    {
      validator: checkSamePassword,
      trigger: 'blur'
    }
  ]
}

// 确认密码是否一致
function checkSamePassword(rule, value, callback) {
  if (value !== formModel.value.new_pwd) {
    return callback(new Error('密码与新密码不一致'))
  }
  return callback()
}

// 用户信息重置
const userStore = useUserStore()
// 路由跳转
const router = useRouter()
// 提交表单
const submit = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    await userEditPasswordService(formModel.value)
    ElMessage.success('修改成功')
    formRef.value.resetFields()
    userStore.setToken('')
    userStore.setUser({})
    router.push('/login')
  }
}
</script>

<template>
  <page-container title="重置密码">
    <el-form
      :model="formModel"
      ref="formRef"
      :rules="rules"
      label-width="auto"
      label-position="left"
      size="large"
      style="width: 400px"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="formModel.old_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="formModel.new_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="re_pwd">
        <el-input v-model="formModel.re_pwd" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交修改</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>
